package zxj.weixin.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * 图片工具类
 * 
 * @author zhuxuejiang
 *
 */
public class ImageUtils {

	static final Base64 BASE_64 = new Base64();

	/**
	 * 将Base64字符串转换为InputStream
	 * 
	 * @param base64Str
	 *                  Base64字符串
	 * @return InputStream
	 */
	public static ByteArrayInputStream base64ToInputStream(String base64Str) {
		return new ByteArrayInputStream(BASE_64.decode(base64Str.getBytes()));
	}

	/**
	 * 将Base64字符串转换为图片文件
	 * 
	 * @param base64Str
	 *                   Base64字符串
	 * @param folderPath
	 *                   图片文件存储的文件夹路径
	 * @return 图片文件路径
	 * @throws IOException
	 */
	public static String base64ToFile(String base64Str, String folderPath) throws IOException {
		// 判断base64Str是否为空
		if (StringUtils.isBlank(base64Str)) {
			return null;
		}

		// 判断folderPath是否为空
		if (StringUtils.isBlank(folderPath)) {
			return null;
		}

		// 截取图片数据
		String[] parts = base64Str.split(",");
		int pathLength = 2;
		if (parts.length != pathLength) {
			return null;
		}

		String ext = parts[0].substring(parts[0].indexOf('/'), parts[0].indexOf(';'));
		ext = ext.substring(1, ext.length());
		String imageStr = parts[1];

		ByteArrayInputStream bis = null;
		String filePath = null;
		try {
			bis = base64ToInputStream(imageStr);
			BufferedImage image = ImageIO.read(bis);
			bis.close();

			filePath = folderPath + File.separatorChar + UUID.randomUUID().toString() + "." + ext;
			File file = new File(filePath);

			// 判断父文件夹是否存在。如果不存在则创建。
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			ImageIO.write(image, ext, file);
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != bis) {
				try {
					bis.close();
				} catch (Exception e) {
					throw e;
				}
			}
		}
		return filePath;
	}

	/**
	 * 将图片转换为Base64字符串
	 * 
	 * @param imgPath
	 *                图片路径
	 * @return 图片Base64字符串
	 * @throws IOException
	 */
	public static String imageToBase64(String imgPath) throws IOException {
		InputStream is = null;
		byte[] data = null;
		try {
			is = new FileInputStream(imgPath);
			data = new byte[is.available()];
			is.read(data);
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (Exception e) {
					throw e;
				}
			}
		}

		return new String(BASE_64.encode(data));
	}

}
